/*
 * ZhuaTu.java
 *
 * Created on __DATE__, __TIME__
 */

package cre.gutwo.swing;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cre.gutwo.handle.DataHandleManager;
import cre.gutwo.service.RuleService;
import cre.gutwo.util.FrameUtil;
import cre.gutwo.util.SpringContextUtil;

/**
 * 
 * @author __USER__
 */
public class HandleFrame extends javax.swing.JFrame implements ActionListener, ListSelectionListener {
	private static final long serialVersionUID = -5942591835548792786L;
	private javax.swing.JButton jButton2;
	private javax.swing.JButton jButton3;

	private javax.swing.JButton jButton4;
	private javax.swing.JButton jButton5;

	private javax.swing.JLabel jLabel1;
	private javax.swing.JRadioButton jRadioButton1;
	private javax.swing.JRadioButton jRadioButton2;
	private JLabel jLabel2;
	private JLabel jLabel3;

	private JTextField textField1;
	private JTextField textField2;

	private JLabel label;
	private JCheckBox checkBox;

	private DataHandleManager dataHandleManager;
	private RuleService ruleService;

	private final ButtonGroup buttonGroup = new ButtonGroup();

	// End of variables declaration//GEN-END:variables

	/** Creates new form ZhuaTu */
	public HandleFrame() {
		initComponents();
		init();

		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				if (SpringContextUtil.getApplicationContext() == null) {
					new ClassPathXmlApplicationContext("applicationContext.xml");
				}
			}
		}, 0, 100);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {
		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		// label
		jLabel1 = new javax.swing.JLabel();
		jLabel1.setText("源数据");

		jLabel2 = new JLabel();
		jLabel2.setText("目标数据");

		jLabel3 = new JLabel();
		jLabel3.setText("数据类型");
		// radio
		jRadioButton1 = new javax.swing.JRadioButton();
		jRadioButton2 = new javax.swing.JRadioButton();

		jRadioButton1.setSelected(true);
		jRadioButton1.setText("硬件列表");
		jRadioButton1.setName("type");

		jRadioButton2.setText("软件列表");
		jRadioButton2.setName("type");

		buttonGroup.add(jRadioButton1);
		buttonGroup.add(jRadioButton2);
		jButton2 = new javax.swing.JButton("生成文件");
		jButton3 = new javax.swing.JButton("初始化对照表");

		// 文件选择器
		textField1 = new JTextField();
		textField1.setColumns(10);

		textField2 = new JTextField();
		textField2.setColumns(10);
		textField2.setText(System.getProperty("user.home"));

		jButton4 = new JButton("浏览");
		jButton5 = new JButton("浏览");

		label = new JLabel("详细过程");
		checkBox = new JCheckBox("显示");
		checkBox.setSelected(true);

		initLayout();

		pack();
	}// </editor-fold>
		// GEN-END:initComponents

	private void initLayout() {
		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
				.addGroup(layout.createSequentialGroup().addContainerGap()
						.addGroup(layout.createParallelGroup(Alignment.LEADING)
								.addGroup(layout.createSequentialGroup()
										.addGroup(layout.createParallelGroup(Alignment.TRAILING)
												.addGroup(layout.createSequentialGroup().addComponent(jButton2)
														.addPreferredGap(ComponentPlacement.RELATED))
								.addGroup(layout.createSequentialGroup()
										.addGroup(layout.createParallelGroup(Alignment.LEADING)
												.addGroup(Alignment.TRAILING,
														layout.createSequentialGroup()
																.addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, 48,
																		GroupLayout.PREFERRED_SIZE)
																.addGap(49))
												.addGroup(
														layout.createSequentialGroup().addComponent(label).addGap(49)))
										.addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(checkBox)
												.addComponent(jRadioButton1))
										.addPreferredGap(ComponentPlacement.RELATED)))
						.addGroup(layout.createParallelGroup(Alignment.LEADING)
								.addGroup(layout.createSequentialGroup().addGap(41).addComponent(jRadioButton2))
								.addGroup(layout.createSequentialGroup().addGap(86).addComponent(jButton3))))
						.addGroup(layout.createSequentialGroup()
								.addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(jLabel1)
										.addComponent(jLabel2))
								.addGap(41)
								.addGroup(layout.createParallelGroup(Alignment.LEADING, false).addComponent(textField2)
										.addComponent(textField1, GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(jButton5)
										.addComponent(jButton4))))
						.addContainerGap(175, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING)
				.addGroup(layout.createSequentialGroup().addGap(32)
						.addGroup(layout.createParallelGroup(Alignment.BASELINE).addComponent(jLabel1)
								.addComponent(textField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE)
								.addComponent(jButton4))
				.addGap(29)
				.addGroup(layout.createParallelGroup(Alignment.BASELINE).addComponent(jLabel2)
						.addComponent(textField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)
						.addComponent(jButton5))
				.addGap(29)
				.addGroup(layout.createParallelGroup(Alignment.BASELINE).addComponent(jLabel3)
						.addComponent(jRadioButton1).addComponent(jRadioButton2)).addGap(18)
				.addGroup(layout.createParallelGroup(Alignment.BASELINE).addComponent(label).addComponent(checkBox))
				.addPreferredGap(ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
				.addGroup(layout.createParallelGroup(Alignment.BASELINE).addComponent(jButton2).addComponent(jButton3))
				.addContainerGap()));
		getContentPane().setLayout(layout);
	}

	public void init() {

		jButton2.setActionCommand("handle");
		jButton2.addActionListener(this);

		jButton3.setActionCommand("init");
		jButton3.addActionListener(this);

		jButton4.setActionCommand("file1");
		jButton4.addActionListener(this);

		jButton5.setActionCommand("file2");
		jButton5.addActionListener(this);
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				HandleFrame hf = new HandleFrame();
				hf.setTitle("数据转换工具");
				hf.setLocationRelativeTo(null);

				hf.setResizable(false);
				hf.setVisible(true);
			}
		});
		
		
		File f = new File("d.txt");
		System.out.println(f.exists());
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		if ("clear1".equals(command)) {
			textField1.setText("");
			textField2.setText("");

		} else if ("handle".equals(command)) {
			String orgiPath = textField1.getText();
			String destPath = textField2.getText();

			if (StringUtils.isBlank(orgiPath)) {
				JOptionPane.showMessageDialog(this, "请选择源数据文件");
				return;
			}

			if (SpringContextUtil.getApplicationContext() == null) {
				new ClassPathXmlApplicationContext("applicationContext.xml");
			}

			if (StringUtils.isBlank(destPath))
				destPath = cre.gutwo.util.Constants.DEFAULT_DEST_PATH;

			if (dataHandleManager == null)
				dataHandleManager = SpringContextUtil.getBean("dataHandleManager", DataHandleManager.class);

			if (ruleService == null)
				ruleService = SpringContextUtil.getBean("ruleServiceImpl", RuleService.class);

			boolean de = ruleService.deviceInfoEmpty();
			boolean ce = ruleService.companyCodeEmpty();
			if (de || ce) {
				StringBuffer sb = new StringBuffer("当前比照表信息：");
				if (de)
					sb.append("DeviceInfo为空");
				if (de && ce)
					sb.append(",");
				if (ce)
					sb.append("CompanyCode为空");
				sb.append("。");
				sb.append("是否继续？");

				int response = JOptionPane.showOptionDialog(this, sb.toString(),
						UIManager.getString("OptionPane.titleText"), JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE, null, null, null);

				if (response != 0)
					return;
			}

			JPrintStream jps = new JPrintStream(this);
			boolean detailed = checkBox.isSelected();

			String type = "1";
			if (jRadioButton1.isSelected()) {
				type = "1";

				if (detailed) {
					FrameUtil.setOut(jps);
					final String orgiPath2 = orgiPath;
					final String destPath2 = destPath;
					final String type2 = type;

					new Thread(new Runnable() {
						@Override
						public void run() {
							dataHandleManager.handle(orgiPath2, destPath2, type2, null);
						}
					}).start();

				} else {
					FrameUtil.setOut(null);
					dataHandleManager.handle(orgiPath, destPath, type, null);
					alert();
				}

			}
			if (jRadioButton2.isSelected()) {
				type = "2";
				
				if (detailed) {
					FrameUtil.setOut(jps);
					final String orgiPath2 = orgiPath;
					final String destPath2 = destPath;
					final String type2 = type;

					new Thread(new Runnable() {
						@Override
						public void run() {
							dataHandleManager.handle(orgiPath2, destPath2, type2, null);
						}
					}).start();
				} else {
					FrameUtil.setOut(null);
					dataHandleManager.handle(orgiPath, destPath, type, null);
					alert();
				}
			}

		} else if ("init".equals(command)) {
			initCompareFrame();

		} else if ("file1".equals(command)) {
			textField1.setText(gainFilePath(fileChooser()));
		} else if ("file2".equals(command)) {
			textField2.setText(gainFilePath(fileExp()));
		}
	}

	public void alert() {
		JOptionPane.showMessageDialog(this, "数据转换完成，CSV文件创建成功");
	}

	private void initCompareFrame() {
		initCompare();
	}

	protected String gainFilePath(File file) {
		if (file != null)
			return file.getAbsolutePath();

		return null;
	}

	protected void initCompare() {
		setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

		InitCompareFrame hf = new InitCompareFrame();
		hf.setTitle("对照表初始化工具");
		hf.setLocationRelativeTo(null);
		hf.setSize(500, 280);
		hf.setResizable(false);
		hf.setVisible(true);

		setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	}

	FileFilter gainFileFilter() {
		return new FileNameExtensionFilter("excel文件", "xls", "xlsx");
	}

	protected File fileChooser() {
		setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		File result = null;

		// 打开文件选择窗口
		JFileChooser chooser = new JFileChooser();
		chooser.setFileFilter(gainFileFilter());

		int r = chooser.showOpenDialog(this);
		if (r == JFileChooser.APPROVE_OPTION) {
			result = chooser.getSelectedFile();
		} else {
			// 没有选择文件
		}
		setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		return result;
	}

	protected File fileExp() {
		setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		File result = null;

		// 打开文件选择窗口
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

		int r = chooser.showOpenDialog(new JFrame());
		if (r == JFileChooser.APPROVE_OPTION) {
			result = chooser.getSelectedFile();
		} else {
			// 没有选择文件
		}
		setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		return result;
	}
}